package com.example.myapplication.ui

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.*
import android.os.*
import android.util.Base64
import android.util.Log
import com.example.myapplication.base.BaseActivity
import com.example.myapplication.bean.*
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.uitls.JB380ADriver
import com.gprinter.aidl.GpService
import com.gprinter.command.EscCommand
import com.gprinter.command.GpCom
import com.gprinter.command.GpUtils
import com.gprinter.command.LabelCommand
import com.gprinter.io.GpDevice
import com.gprinter.io.PortParameters
import com.gprinter.save.PortParamDataBase
import com.gprinter.service.GpPrintService
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import cpcl.PrinterHelper
import java.util.*

class MainActivity : BaseActivity<ActivityMainBinding>() {
    lateinit var mBluetoothAdapter: BluetoothAdapter
    private var gpIsOpen = false
    var btDeviceString = ""
    private var mPortParam = PortParameters()
    private var scanHandler: Handler? = null

    //汉印打印机的型号
    private var printType = ""

    companion object {
        /**
         * 佳博打印机
         */
        var gpService: GpService? = null
        const val MAIN_QUERY_PRINTER_STATUS = 0xfe
        const val REQUEST_BT_ADDR = 1
    }

    override fun onResume() {
        super.onResume()
        regScan(scanHandler!!)
    }

    override fun initView() {
        scanHandler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == 100) {
                    val scanCode = msg.data.getString("BARCODE")
                    binding.tvCode.text = "${"扫描结果：$scanCode"}"
                    Log.e(
                        "sss",
                        "handleMessage:       $scanCode"
                    )
//                    if (scanCode != null && scanCode.isNotEmpty()) {
//                        if (scanCode.length > 0) {
//                            inventoryBinding.idStoreInventoryNo.setText("")
//                            inventoryModel.event("BARCODE", scanCode)
//                        } else {
//                            toast("请选择正确条码")
//                        }
//                    }
                }
            }
        }
        registerReceiver(mReceiver, IntentFilter(GpCom.ACTION_CONNECT_STATUS))
        registerReceiver(mReceiver, IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED))
        connection()
    }

    override fun initData() {
        binding.tvJiabo.setOnClickListener {
            checkPrintDriver()
        }
        binding.tvHanyin.setOnClickListener {
            checkPrintDriver()
        }
    }

    override fun initLayout() {

    }

    private fun checkPrintDriver() {
        XXPermissions.with(this)
            // 申请定位权限
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
                    if (mBluetoothAdapter == null) {
                        toast("本机没有找到蓝牙硬件或驱动！")
                        finish()
                        return
                    }
                    //功能： 是否正在处于扫描过程中。
                    //注意： 如果蓝牙没有开启，该方法会返回false。
                    if (mBluetoothAdapter.isDiscovering) {
                        //功能： 取消扫描过程。
                        //注意： 如果蓝牙没有开启，该方法会返回false。
                        mBluetoothAdapter.cancelDiscovery()
                    }
                    if (btDeviceString == "") {
                        toast("请先绑定打印机!")
                        gotoBT()
                        return
                    }
                    //佳博打印机
                    try {
                        gpService!!.queryPrinterStatus(
                            0,
                            500,
                            MAIN_QUERY_PRINTER_STATUS
                        )
                    } catch (e: RemoteException) {
                        e.printStackTrace()
                        gpIsOpen = false
                        toast("打印机连接超时！")
                    }
                    Log.e(
                        "jiabo打印",
                        "portOpenState=${mPortParam.portOpenState}"
                    )
                    if (gpIsOpen) {
                        toast("打印")
//                        sendLabel()
                        var map = HashMap<String, String>()
                        map["text"] = "测试居中"
                        map["barcode"] = "20067001200670012"

                        var printerSpec = HashMap<String, TextElementPrinterSpec>()
                        printerSpec["佳博-380A"] =
                            TextElementPrinterSpec(LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE.value)

                        var printTemplate = PrintTemplate(
                            PrintPageParameter(70, 40), listOf(
                                BoxElement(0, 0, 550, 230, 4),
                                LineElement(0, 60, 550, 4, 4),
                                TextElement(0, 10, 550, 0, listOf(), "CENTER", 2, printerSpec),
                                BarCodeElement(0, 238, 40)
                            )
                        )
                        JB380ADriver(gpService!!).Print(map, printTemplate)
                        return
                    }
                    //汉印打印机
                    try {
                        if (PrinterHelper.IsOpened()) {
//                            sendHprtPrinting()
                            return
                        }
                    } catch (e: Exception) {
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {

                }
            })
    }

    /**
     * 佳博380A打印
     */
    fun sendLabel() {
        val ticket_receive_name = "一号车间"
        val ticket_orderid //单号
                = "2202302270905000001"
        val ticket_count //件数
                = 10
        val ticket_count_start //开始范围
                = 0
        val ticket_count_end //结束范围
                = 10
        val ticket_sendtype //选择的是普、快、件
                = "普件"
        val ticket_startbranch //发货网点
                = "安踏有限公司"
        val ticket_destinationbranch //到货网点
                = "一号车间"
        val ticket_cargotype //包装类型
                = "袋"
        var ticket_delivery_type = "送"

        val str: String = ticket_receive_name
        val len = (360 / 2 - str.length * 50 / 2).toString()
        val str1: String = ticket_sendtype //普快件
        val str1Len = (80 / 2 - str1.length * 10 / 2).toString()
        var comPanyRow_copy = "安踏有限公司"

        var tsc = LabelCommand()
        /**
         * 设置标签尺寸，按照实际尺寸设置
         */
        tsc.addSize(70, 40)
        /**
         * 打印时的浓度
         */
        tsc.addDensity(LabelCommand.DENSITY.DNESITY15)
        /**
         * 设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0
         */
        tsc.addGap(1)
        /**
         * 设置打印速度
         */
        tsc.addSpeed(LabelCommand.SPEED.SPEED4)
        /**
         * 设置打印方向
         */
        tsc.addDirection(LabelCommand.DIRECTION.BACKWARD, LabelCommand.MIRROR.NORMAL)
        /**
         * 开启带Response的打印，用于连续打印
         */
        tsc.addQueryPrinterStatus(LabelCommand.RESPONSE_MODE.ON)
        /**
         * 设置原点坐标，用于连续打印
         */
        tsc.addReference(0, 0)
        /**
         * 撕纸模式开启
         */
        tsc.addTear(EscCommand.ENABLE.ON)
        /**
         * 清除打印缓冲区
         */
        tsc.addCls()

        /**addText
        x 文字 X 方向起始点坐标
        y 文字 Y 方向起始点坐标
        font SIMPLIFIED_CHINESE 字体名称
        rotation 文字旋转角度（顺时针方向）
        x-multiplication X 方向放大倍率 1-10
        y-multiplication Y 方向放大倍率 1-10
         */
        //打印收件人
        tsc.addText(
            360 / 2 - str.length * 40 / 2,
            10,
            LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,
            LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_2,
            LabelCommand.FONTMUL.MUL_2,
            str
        )
        //打印包装类型
        tsc.addText(
            360, 35, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1, ticket_cargotype
        )

        //打印包装件
        tsc.addText(
            410,
            10,
            LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,
            LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_1,
            LabelCommand.FONTMUL.MUL_1,
            "${"$ticket_count_start/$ticket_count"}"
        )
        //打印出发地址
        tsc.addText(
            10, 70, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_2, ticket_startbranch + "->"
        )
        //打印目的地址
        tsc.addText(
            10, 120, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2, ticket_destinationbranch
        )


        //出现汉字比较多一排写不下，此处用两个Text
        tsc.addText(
            360, 70, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2, ticket_orderid.substring(0, 6)
        )
        tsc.addText(
            360,
            120,
            LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,
            LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_2,
            LabelCommand.FONTMUL.MUL_2,
            ticket_orderid.substring(6, ticket_orderid.length)
        )


        //普件 快件打印
        tsc.addText(
            10, 190, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1, str1
        )
        //普件快件内容
        if (comPanyRow_copy.length <= 6) {
            tsc.addText(
                120,
                190,
                LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,
                LabelCommand.ROTATION.ROTATION_0,
                LabelCommand.FONTMUL.MUL_1,
                LabelCommand.FONTMUL.MUL_1,
                comPanyRow_copy
            )
        } else {
            tsc.addText(
                120, 190, LabelCommand.FONTTYPE.FONT_1, LabelCommand.ROTATION.ROTATION_0,
                LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1, comPanyRow_copy
            )
        }
        //打印时间
        tsc.addText(
            355, 190, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1, "2023年02月27日"
        )
        //打印“盛辉”
        tsc.addText(
            0, 240, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0,
            LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2, "盛辉"
        )
        /**
        x 左上角水平坐标起点，以点（dot）表示
        y 左上角垂直坐标起点，以点（dot）表示
        type CODE128编码类型
        height 条形码高度，以点（dot）表示
        LabelCommand.READABEL.EANBEL  0 表示人眼不可识，1 表示人眼可识
        rotation 条形码旋转角度，顺时针方向
        narrow 窄 bar 宽度，以点（dot）表示
        width 宽 bar 宽度，以点（dot）表示
        printorder 打印内容
         */
        //打印条形码
        tsc.add1DBarcode(
            120, 238, LabelCommand.BARCODETYPE.CODE128, 40,
            LabelCommand.READABEL.DISABLE, LabelCommand.ROTATION.ROTATION_0, 3, 400, ticket_orderid
        )

        //打印条形码下对应运单号
//        tsc.addText(
//            120,
//            285,
//            LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,
//            LabelCommand.ROTATION.ROTATION_0,
//            LabelCommand.FONTMUL.MUL_1,
//            LabelCommand.FONTMUL.MUL_1,
//            printorder
//        )

        //四条横线
        tsc.addBar(0, 0, 550, 4)
        tsc.addBar(0, 60, 550, 4)
        tsc.addBar(1, 180, 550, 4)
        tsc.addBar(1, 230, 550, 4)
        //四条竖线
        tsc.addBar(1, 0, 4, 230)
        tsc.addBar(350, 0, 4, 230)
        tsc.addBar(550, 0, 4, 230)
        tsc.addBar(130, 180, 4, 50)
        tsc.addPrint(1, 1) //1份1张 打印标签
        val datas = tsc.command // 发送数据
        val bytes = GpUtils.ByteTo_byte(datas)
        val data = Base64.encodeToString(bytes, Base64.DEFAULT)
        try {
            val rel = gpService!!.sendLabelCommand(0, data)
            val r = GpCom.ERROR_CODE.values()[rel]
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                Log.e("jiabo", "dayinbuchengong---------------------${GpCom.getErrorText(r)}")
            }
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    }

    //汉印
    @Throws(java.lang.Exception::class)
    private fun sendHprtPrinting() {
        val print_type //判断连接的哪个打印机
                = 0
        val ticket_receive_name = "一号车间"
        val ticket_orderid //单号
                = "2202302270905000001"
        val ticket_count //件数
                = 10
        val ticket_count_start //开始范围
                = 0
        val ticket_count_end //结束范围
                = 10
        val ticket_sendtype //选择的是普、快、件
                = "普件"
        val ticket_startbranch //发货网点
                = "安踏有限公司"
        val ticket_destinationbranch //到货网点
                = "一号车间"
        val ticket_cargotype //包装类型
                = "袋"
        var ticket_delivery_type = "送"

        val str: String = ticket_receive_name
        val len = (360 / 2 - str.length * 50 / 2).toString()
        val str1: String = ticket_sendtype //普快件
        val str1Len = (80 / 2 - str1.length * 10 / 2).toString()
        var comPanyRow_copy = "安踏有限公司"

        try {
            val orderStr = "$ticket_count_start${"/$ticket_count_end"}"
            /**printAreaSize设置标签高度
            "0" 上下文对象
            "200" 打印机水平方向dpi（根据实际打印机dpi设置）
            "200" 打印机垂直方向dpi（根据实际打印机dpi设置）
            "370" 标签高度 （单位：dot）200dpi 8 dot = 1mm，300dpi 12 dot = 1mm
            "1" 打印次数
             */
            PrinterHelper.printAreaSize("0", "200", "200", "370", "1")
            /**Box
            {x0} 左上角的 X 坐标
            {y0} 左上角的 Y 坐标
            {x1} 右下角的 X 坐标
            {y1} 右下角的 Y 坐标
            {width} 形成矩形框的线条的单位宽度
             **/
            PrinterHelper.Box("0", "7", "570", "240", "5")
            /**Line
            {x0} 起始点的 X 坐标
            {y0} 起始点的 Y 坐标
            {x1} 终止点的 X 坐标
            {y1} 终止点的 Y 坐标
            {width} 线条的单位宽度
             **/
            PrinterHelper.Line("0", "63", "570", "63", "5")
            PrinterHelper.Line("0", "173", "570", "173", "5")

            PrinterHelper.Line("350", "7", "350", "235", "5")
            if (str1.length == 3) {
                PrinterHelper.Line("150", "173", "150", "230", "5")
            } else {
                PrinterHelper.Line("120", "173", "120", "230", "5")
            }
            /**SetMag 字体放大
            {w} 宽度放大倍数，有效放大倍数为1 到16
            {h} 高度放大倍数，有效放大倍数为1 到16
             **/
            PrinterHelper.SetMag("2", "2")
            /**Text
            s1 TEXT,TEXT_Anti_White,TEXT90,TEXT180,TEXT270
            {font} 字体名称/编号"8"= 英文字体12*24 中文字体24*24 简体中文 GB18030 "4"=16*32 32*32 简体中文 GBK
            {size} 忽略该参数，请输入任意数字
            {x} 横向起始位置
            {y} 纵向起始位置
            {str} 要打印的文本
             **/
            PrinterHelper.Text(PrinterHelper.TEXT, "8", "0", len, "15", str)
            PrinterHelper.SetMag("1", "1")
            if (printType == "HM-A") PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "15",
                "75",
                ticket_startbranch + " - >"
            ) else PrinterHelper.Text(
                PrinterHelper.TEXT,
                "4",
                "0",
                "15",
                "75",
                ticket_startbranch + " - >"
            )
            PrinterHelper.SetMag("2", "2")
            PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "45",
                "120",
                ticket_destinationbranch
            )
            PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "380",
                "75",
                ticket_orderid.substring(0, 5)
            )
            PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "380",
                "125",
                ticket_orderid.substring(5)
            )
            PrinterHelper.SetMag("1", "1")
            if (printType == "HM-A") PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "460",
                "15",
                orderStr
            ) else PrinterHelper.Text(PrinterHelper.TEXT, "4", "0", "460", "15", orderStr)
            if (printType == "HM-A") PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "380",
                "38",
                ticket_cargotype
            ) else PrinterHelper.Text(
                PrinterHelper.TEXT,
                "4",
                "0",
                "380",
                "30",
                ticket_cargotype
            )
            PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                "365",
                "195",
                "2023年02月27日"
            )
            if (printType == "HM-A") PrinterHelper.Text(
                PrinterHelper.TEXT,
                "8",
                "0",
                str1Len,
                "195",
                str1
            ) else PrinterHelper.Text(PrinterHelper.TEXT, "4", "0", str1Len, "190", str1)
            if (str1.length == 3) {
                PrinterHelper.Text(PrinterHelper.TEXT, "8", "0", "160", "190", comPanyRow_copy)
            } else {
                PrinterHelper.Text(PrinterHelper.TEXT, "8", "0", "150", "190", comPanyRow_copy)
            }
            PrinterHelper.SetMag("2", "2")
            PrinterHelper.Text(PrinterHelper.TEXT, "8", "0", "13", "245", "盛辉")
            PrinterHelper.SetMag("1.7", "1.7")

            //底部单号
            val printorder = ticket_orderid

            if (ticket_delivery_type != "") {
                //底部单号
                if (printType == "HM-A") PrinterHelper.Text(
                    PrinterHelper.TEXT,
                    "8",
                    "0",
                    "128",
                    "300",
                    printorder
                ) else PrinterHelper.Text(
                    PrinterHelper.TEXT,
                    "4",
                    "0",
                    "128",
                    "300",
                    printorder
                )
                /**Barcode
                BARCODE 横向打印条码 VBARCODE 纵向打印条码
                条码种类code128 理想宽窄比N/A 理想窄点宽度2
                "1"= 宽窄比2.0:1 "2"=2.5:1
                {2} 窄条的单位宽度
                {40} 宽条与窄条的比率
                {height} 条码的单位高度
                {118} 横向起始位置
                {245} 纵向起始位置
                第8个参数=false 后三位参数可以忽略
                {printorder} 条码数据
                 */
                PrinterHelper.Barcode(
                    PrinterHelper.BARCODE,
                    PrinterHelper.code128,
                    "1",
                    "2",
                    "40",
                    "118",
                    "245",
                    false,
                    "7",
                    "20",
                    "5",
                    printorder
                )
                PrinterHelper.SetMag("2", "2")
                PrinterHelper.Text(
                    PrinterHelper.TEXT, "8", "0", "470", "245",
                    "[$ticket_delivery_type]"
                )
            } else {
                //底部单号
                if (printType == "HM-A") PrinterHelper.Text(
                    PrinterHelper.TEXT,
                    "8",
                    "0",
                    "200",
                    "300",
                    printorder
                ) else PrinterHelper.Text(
                    PrinterHelper.TEXT,
                    "4",
                    "0",
                    "200",
                    "300",
                    printorder
                )
                PrinterHelper.Barcode(
                    PrinterHelper.BARCODE,
                    PrinterHelper.code128,
                    "2",
                    "1",
                    "40",
                    "118",
                    "245",
                    false,
                    "7",
                    "20",
                    "5",
                    printorder
                )
            }
            PrinterHelper.Form()//打印标签定位作用（连续纸不可用）
            PrinterHelper.Print()//打印
        } catch (e: java.lang.Exception) {
        }
    }

    /**
     * 去蓝牙
     */

    private fun gotoBT() {
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled) {
                mBluetoothAdapter.enable()
            }
        }
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (mBluetoothAdapter.isDiscovering) { //是否正在搜索设备，是TRUE
            mBluetoothAdapter.cancelDiscovery()
        }
        val myIntent = Intent(this, BluetoothPrintActivity::class.java)
        startActivityForResult(
            myIntent,
            REQUEST_BT_ADDR
        )
    }

    /**
     * 佳博打印机绑定服务
     */
    private fun connection() {
        var conn = PrinterServiceConnection()
        val intent = Intent(this, GpPrintService::class.java)
        bindService(intent, conn, Context.BIND_AUTO_CREATE)
        val database = PortParamDataBase(this)
        mPortParam = database.queryPortParamDataBase("" + 0)
        mPortParam.portOpenState = false
    }

    /**
     * 佳博打印机服务
     */
    class PrinterServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            gpService = GpService.Stub.asInterface(service)
        }

        override fun onServiceDisconnected(name: ComponentName) {
            gpService = null
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_BT_ADDR) {
            if (data == null) return
            val deviceNameStr =
                data.getStringExtra(BluetoothPrintActivity.EXTRA_BLUETOOTH_DEVICE_NAME)
            btDeviceString =
                data.getStringExtra(BluetoothPrintActivity.EXTRA_BLUETOOTH_DEVICE_ADDRESS)
                    .toString()
            Log.e(
                "sss1",
                "deviceNameStr:            $deviceNameStr" +
                        "btDeviceString:            $btDeviceString"

            )
            if (deviceNameStr!!.startsWith("Printer") || deviceNameStr.startsWith("ZH")) {
                object : Thread() {
                    override fun run() {
                        try {
                            //初始化打印机参数
                            mPortParam.portType = PortParameters.BLUETOOTH
                            mPortParam.bluetoothAddr = btDeviceString
                            if (mPortParam.portOpenState) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    try {
                                        Log.e("jiabo", "========关闭前========")
                                        gpService!!.closePort(0)
                                        Log.e("jiabo", "========关闭后========")
                                    } catch (e: RemoteException) {
                                        e.printStackTrace()
                                    }
                                } else {
                                    mBluetoothAdapter.disable()
                                    if (mBluetoothAdapter != null) {
                                        mBluetoothAdapter.enable()
                                        sleep(2000)
                                    }
                                }
                            }
                            val rel = gpService!!.openPort(
                                0,
                                mPortParam.getPortType(),
                                mPortParam.getBluetoothAddr(),
                                0
                            )
                            val r = GpCom.ERROR_CODE.values()[rel]
                            Log.e(
                                "jiabosleep",
                                "r=========$r==========portOpenState=${mPortParam.portOpenState}"
                            )
                            sleep(5000)

                            if (r != GpCom.ERROR_CODE.SUCCESS) {
                                if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                                    mPortParam.portOpenState = true
                                } else {
                                    toast("打印机打开失败")
                                    return
                                }
                            }
                            Log.e(
                                "jiabosleep后",
                                "r=========$r=====portOpenState=${mPortParam.portOpenState}"
                            )
                            val filter = IntentFilter()
                            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) // 蓝牙断开
                            registerReceiver(mReceiver, filter)
                        } catch (ee: Exception) {
                            ee.printStackTrace()
                        }
                    }
                }.start()
            } else if (deviceNameStr.startsWith("HM-A")) {
                printType = "HM-A"
                if (mBluetoothAdapter.isDiscovering) mBluetoothAdapter.cancelDiscovery()
                Thread(Runnable {
                    //关闭佳博打印机
                    if (mPortParam.portOpenState) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            try {
                                Log.e("jiabo", "========关闭前========")
                                gpService!!.closePort(0)
                                Log.e("jiabo", "========关闭后========")
                            } catch (e: RemoteException) {
                                e.printStackTrace()
                            }
                        } else {
                            mBluetoothAdapter.disable()
                            if (mBluetoothAdapter != null) {
                                mBluetoothAdapter.enable()
                            }
                        }
                    }
                    try {
                        Thread.sleep(5000)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    try {
                        val portOpen = PrinterHelper.portOpenBT(this, btDeviceString)
                        if (portOpen == 0) {
                            Log.e(
                                "hanyin",
                                "run:              打印机链接成功 "
                            )
                            //     PrinterHelper.portClose();//关闭
                        } else {
                            toast("打印机Open失败")
                            Log.e(
                                "hanyin",
                                "run:           蓝牙打印机打开失败  "
                            )
                            return@Runnable
                        }
                    } catch (e: java.lang.Exception) {
                    }
                    val filter = IntentFilter()
                    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) // 蓝牙断开
                    registerReceiver(mReceiver, filter)
                }).start()
            }
        }
    }

    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.e(
                "jiaboaction",
                "action==============$action"
            )
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED == action) {
                toast("蓝牙已断开");
            } else if (BluetoothDevice.ACTION_ACL_CONNECTED == action) {
                toast("蓝牙连接成功")
            }
            //佳博打印机广播接收打印机状态
            if (GpCom.ACTION_DEVICE_REAL_STATUS == action) {
                // 业务逻辑的请求码，对应哪里查询做什么操作
                val requestCode = intent.getIntExtra(GpCom.EXTRA_PRINTER_REQUEST_CODE, -1)
                // 判断请求码，是则进行业务操作
                if (requestCode == MAIN_QUERY_PRINTER_STATUS) {
                    val status = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS, 16)
                    var str: String
                    if (status == GpCom.STATE_NO_ERR) {
                        str = "打印机正常"
                        gpIsOpen = true
                    } else {
                        str = "打印机 "
                        if ((status and GpCom.STATE_OFFLINE).toByte() > 0) {
                            str += "脱机"
                        }
                        if ((status and GpCom.STATE_PAPER_ERR).toByte() > 0) {
                            str += "缺纸"
                        }
                        if ((status and GpCom.STATE_COVER_OPEN).toByte() > 0) {
                            str += "纸仓盖未关闭"
                        }
                        if ((status and GpCom.STATE_TIMES_OUT).toByte() > 0) {
                            str = "获取打印机状态失败"
                        }
                        gpIsOpen = false
                    }
                    Log.e(
                        "jiabo4",
                        "str==============$str=======$gpIsOpen=====$gpIsOpen"
                    )
                }
            } else if (GpCom.ACTION_CONNECT_STATUS == intent.action) {
                val type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0)
                val id = intent.getIntExtra(GpPrintService.PRINTER_ID, 0)
                var gpStatus = ""
                if (type == GpDevice.STATE_CONNECTING) {
                    gpStatus = "正在连接"
                    gpIsOpen = false
                    mPortParam.portOpenState = false
                } else if (type == GpDevice.STATE_NONE) {
                    gpStatus = "连接断开"
                    gpIsOpen = false
                    mPortParam.portOpenState = false
                } else if (type == GpDevice.STATE_VALID_PRINTER) {
                    gpStatus = "有效的打印机"
                    gpIsOpen = true
                    mPortParam.portOpenState = true
                } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                    gpStatus = "无效的打印机"
                    gpIsOpen = false
                    mPortParam.portOpenState = false
                }
                Log.e(
                    "jiabo3",
                    "=====$gpIsOpen=======${mPortParam.portOpenState}==gpStatus${gpStatus}"
                )
            }
        }
    }
}